import { watch } from 'vue'
import type { Ref } from 'vue'
import { useLS } from '../localStorage/useLs'

const watchObj = (key = '', data: any = {}, cb?: Function) => {
  const { get, set } = useLS(key)
  const result = get()
  if (result) {
    data.value = result
    cb && cb(data.value)
  } else {
    // *无数据 初始化
    set(data.value)
  }

  watch(data, value => {
    set(value)
    cb && cb(value)
  })
}

/**
 * 基于 pinia 持久化数据
 * @param sources 持久化数据源 ref[]
 */
export const usePiniaStorage = (
  sources: { [x: string]: Ref<any> },
  watchs: { [x: string]: Function } = {}
) => {
  Object.keys(sources).forEach(key => watchObj(key, sources[key], watchs[key]))
  return sources
}
